<template>
  <el-form
    :model="editCustomerData"
    v-loading="loading"
    label-position="left"
    size="small"
    :rules="rules"
    ref="approvalform"
    label-width="150px"
    class="project-form"
  >
    <template>
      <el-form-item label="业务模式" prop="is_pro_dir">
        <c-select
          v-if="isUnion"
          :options="enumIsPro"
          v-model="editCustomerData.is_pro_dir"
          placeholder="请选择业务模式"
          class="form-control-ml"
        ></c-select>
        <span v-else>联担业务</span>
      </el-form-item>

      <el-form-item
        label="联保机构"
        prop="gua_service_id"
        v-if="isUnionType"
        :rules="{
          required: true,
          message: '请选择联保机构',
          trigger: 'change',
        }"
      >
        <select-org-credit
          :is-pro="true"
          v-model="editCustomerData.gua_service_id"
          @select="handleAccessAgencyChange"
          class="form-control-ml"
          placeholder="请选择担保机构"
        ></select-org-credit>
      </el-form-item>
    </template>

    <el-form-item label="项目行业分类" prop="ind_class_code">
      <select-parent-main
        placeholder="请选择行业分类"
        class="form-control-ml"
        v-model="editCustomerData.ind_class_code"
        @select="handleSelectIndClass"
      ></select-parent-main>
    </el-form-item>

    <el-form-item label="贷款具体用途" prop="use_category">
      <select-funds-user
        v-model="editCustomerData.use_category"
        :parent-id="editCustomerData.ind_class_code || ''"
        @select="setUserLabel"
        class="form-control-ml"
        placeholder="请输入贷款具体用途"
      ></select-funds-user>
    </el-form-item>

    <el-form-item label="项目负责人: A角" prop="res_a">
      <!-- :isDefaultDept="+editCustomerData.gua_type === 4" -->
      <select-staff
        v-model="editCustomerData.res_a"
        ref="resA"
        class="form-control-ml"
        placeholder="请选择项目负责人: A角"
      ></select-staff>
    </el-form-item>
    <el-form-item label="项目负责人: B角" prop="res_b">
      <select-staff
        v-model="editCustomerData.res_b"
        ref="resB"
        class="form-control-ml"
        placeholder="请选择项目负责人: B角"
      ></select-staff>
    </el-form-item>

    <el-form-item label="产品选择" prop="project_type_id">
      <select-credit-product
        placeholder="请选择担保产品（非必填）"
        class="form-control-ml"
        clearable
        v-model="editCustomerData.project_type_id"
        @change="setLoanMode"
        :project-type="editCustomerData.gua_type"
      ></select-credit-product>
    </el-form-item>

    <el-form-item label="是否新农直通车">
      <el-radio-group v-model="editCustomerData.is_xlzt">
        <el-radio label="1">是</el-radio>
        <el-radio label="0">否</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="产品通道" prop="product_channel">
      <select-product-channel
        v-model="editCustomerData.product_channel"
        palceholder="产品通道"
        class="form-control-ml"
        clearable
      ></select-product-channel>
    </el-form-item>

    <el-form-item label="五大专班" prop="five_ind_class">
      <select-five-ind-class
        v-model="editCustomerData.five_ind_class"
        palceholder="五大专班"
        class="form-control-ml"
        clearable
      ></select-five-ind-class>
    </el-form-item>

    <el-form-item label="指定银行">
      <select-org-bank
        ref="bank"
        v-model="editCustomerData.bank_id"
        :project-type="editCustomerData.gua_type"
        placeholder="选择指定银行（非必填）"
        @select="setPublicName"
        filterable
        clearable
        class="form-control-ml"
      ></select-org-bank>
      <el-button
        type="primary"
        size="small"
        :loading="refreshLoading"
        @click="refreshBank"
        icon="el-icon-refresh"
      ></el-button>
    </el-form-item>

    <el-form-item>
      <div v-if="isEditProject">
        <small class="text-danger">请先修改完善基本信息再受理</small>
      </div>
      <div v-else>
        <el-button type="primary" :loading="saveLoading" class="btn-long" @click="submitForm">
          受理
        </el-button>
        <el-button
          v-if="myProject"
          type="danger"
          :loading="saveLoading"
          class="btn-long"
          @click="handleRefuse"
        >
          拒绝
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectOrgCredit from '@/credit/views/county/unionProvince/components/item/SelectCredit'
import SelectParentMain from '@/bank/views/limit/SelectParentMain.vue'
import SelectFundsUser from '@/bank/views/limit/SelectFundsUser.vue'
import SelectStaff from '@/components/select/SelectStaff'
import SelectCreditProduct from '@/credit/components/select/SelectCreditProduct'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import SelectProductChannel from '@/credit/views/city/program/new/components/SelectProductChannel'
import SelectFiveIndClass from '@/credit/views/city/program/new/components/SelectFiveIndClass'
export const enumIsPro = {
  0: '联担业务',
  1: '直担业务',
}
export default {
  components: {
    SelectOrgCredit,
    SelectParentMain,
    SelectFundsUser,
    SelectStaff,
    SelectCreditProduct,
    SelectOrgBank,
    SelectProductChannel,
    SelectFiveIndClass,
  },
  props: {
    queryId: String,
    isCommonProject: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const isEqPersonValidator = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (this.editCustomerData.res_b === this.editCustomerData.res_a) {
        callback(new Error('项目A角与项目B角不能为同一个人'))
      } else {
        callback()
      }
    }
    return {
      enumIsPro,
      saveLoading: false,
      loading: false,
      editCustomerData: {},
      rules: {
        ind_class_code: { required: true, message: '请选择项目行业类型', trigger: 'change' },
        use_category: { required: true, message: '请选择贷款具体用途', trigger: 'change' },
        res_a: [
          { required: true, message: '请选择A角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        res_b: [
          { required: true, message: '请选择B角', trigger: 'change' },
          { validator: isEqPersonValidator, trigger: 'change' },
        ],
        product_channel: { required: true, message: '请选择产品通道', trigger: 'change' },
        five_ind_class: { required: true, message: '请选择五大专班', trigger: 'change' },
      },
      tableName: 'customer_related',
      refreshLoading: false,
      tableData: {},
    }
  },
  computed: {
    ...mapGetters(['clientId', 'user', 'org']),
    isUnion() {
      return this.user?.scopeArr?.includes('dirGuaPro') ?? false
    },
    // 是否需要选择联保机构
    isUnionType() {
      return +this.editCustomerData.is_pro_dir === 0 && +this.editCustomerData.gua_type === 4
    },
    myProject() {
      return !this.isCommonProject
    },
    isEditProject() {
      // 后端根据历史数据生成项目缺失信息，影响项目流程，受理时判断一些必填值空则提示客户先完善信息
      const keys = ['address_code', 'mobile_no', 'funds_use_dir']
      for (let key of keys) {
        if (!this.tableData[key]) {
          return true
        }
      }
      return false
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async refreshBank() {
      this.refreshLoading = true
      await this.$refs.bank?.getBanks()
      this.refreshLoading = false
    },
    setLoanMode(_, select) {
      this.editCustomerData.project_type_name = select.load_name || ''
    },
    handleAccessAgencyChange(agency) {
      this.editCustomerData.gua_service_name = agency?.agency_name || ''
    },
    setPublicName(bank) {
      this.editCustomerData.bank_type = bank.agency_type_sub || ''
      this.editCustomerData.bank_name = bank.agency_name || ''
    },
    handleSelectIndClass(_, select) {
      this.editCustomerData.use_category = ''
      this.editCustomerData.ind_class_name = select.value || ''
    },
    setUserLabel(select) {
      this.editCustomerData.use_category_name = select.value || ''
    },
    submitForm() {
      this.$refs.approvalform.validate(valid => {
        if (valid) {
          this.submitData()
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    submitData() {
      this.saveLoading = true
      const data = {
        gua_type: this.editCustomerData.gua_type,
        res_a: this.editCustomerData.res_a,
        res_b: this.editCustomerData.res_b,
        res_a_name: (this.$refs.resA && this.$refs.resA.getSelectedName()) || '',
        res_b_name: (this.$refs.resB && this.$refs.resB.getSelectedName()) || '',
        gua_service_name: this.isUnionType ? this.editCustomerData.gua_service_name : '',
        gua_service_id: this.isUnionType ? this.editCustomerData.gua_service_id : '',
        project_type_id: this.editCustomerData.project_type_id || '',
        project_type_name: this.editCustomerData.project_type_name || '',
        bank_id: this.editCustomerData.bank_id || '',
        bank_name: this.editCustomerData.bank_name,
        bank_type: this.editCustomerData.bank_type,
        is_approval: 1,
        approved_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        approval_person: this.user.realName,
        service_id: this.clientId,
        ind_class_code: this.editCustomerData.ind_class_code,
        ind_class_name: this.editCustomerData.ind_class_name,
        use_category: this.editCustomerData.use_category,
        use_category_name: this.editCustomerData.use_category_name,
        is_pro_dir: this.editCustomerData.is_pro_dir || 0,
        is_xlzt: this.editCustomerData.is_xlzt || '0',
        product_channel: this.editCustomerData.product_channel,
        five_ind_class: this.editCustomerData.five_ind_class,
      }
      if (+(this.editCustomerData.is_pro_dir || '') === 1) {
        data.join_risk_rate_qx = 0
      }
      this.$api
        .updateData(this.$serviceName, this.tableName, this.queryId, data)
        .then(() => {
          this.$emit('close', false)
          this.$emit('success', true)
          this.$message.success('受理成功')
        })
        .catch(err => {
          if (err) {
            const errStr =
              typeof err.data?.error_description === 'string'
                ? err.data?.error_description
                : '操作失败，请重试！'
            return this.$message.error(`${errStr}`)
          }
        })
        .finally(() => {
          this.saveLoading = false
        })
    },
    handleRefuse() {
      if (!this.queryId) {
        return
      }
      this.$prompt('请输入拒绝理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入不通过原因' : true),
      })
        .then(({ value }) => {
          this.saveLoading = true
          this.$api
            .updateData(this.$serviceName, 'customer_related', this.queryId, {
              confuse_status: 3,
              confuse_time: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
              confuse_person: this.user.realName,
              confuse_des: value,
              is_approval: 2,
              approved_date: this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
            })
            .then(() => {
              this.$emit('close', true)
              this.$emit('success', true)
              this.$message.success('项目已拒绝')
            })
            .catch(() => {
              this.$message.error(`项目拒绝失败，请重试`)
            })
            .finally(() => {
              this.saveLoading = false
            })
        })
        .catch(() => {})
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, this.tableName, this.queryId)
        .then(res => {
          this.tableData = res?.data ?? {}
          this.editCustomerData = {
            ...this.tableData,
            gua_type: 4,
          }
        })
        .finally(() => {
          this.$nextTick(() => {
            this.$refs.approvalform?.clearValidate()
          })
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
